package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikeTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2025-10-28
 */
@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final RabbitMqHelper mqHelper;


    /**
     * 点赞或取消点赞
     *
     * @param formDTO
     */
    @Override
    public void likeOrUnlike(LikeRecordFormDTO formDTO) {
        // 1、判断点赞还是取消点赞，根据判断结果执行点赞、取消点赞的业务逻辑
        boolean isSuccess = formDTO.getLiked() ? like(formDTO) : unLike(formDTO);

        // 2、判断是否执行成功，如果失败，直接结束
        if (!isSuccess) {
            return;
        }

        // 3、如果执行成功，则统计点赞数
        Integer likeTimes = this.lambdaQuery().eq(LikedRecord::getBizId, formDTO.getBizId()).count();

        // 4、发送MQ消息，通知业务方修改点赞数
        mqHelper.send(
                LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,formDTO.getBizType()),  // QA.times.changed  NOTE.times.changed
                LikeTimesDTO.of(formDTO.getBizId(), likeTimes)
        );
    }

    /**
     * 根据业务ID集合查询点赞状态
     *
     * @param bizIds  1,2
     */
    @Override
    public Set<Long> isLiked(List<Long> bizIds) {
        // 1、查询点赞记录
        // select biz_id from liked_record where user_id = ? and biz_id in (?)
        List<LikedRecord> list = this.lambdaQuery()
                .select(LikedRecord::getBizId)
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .in(LikedRecord::getBizId, bizIds)
                .list();
        if(ObjectUtils.isEmpty(list)){
            return Collections.emptySet();
        }
        // 2、返回已经点赞的ID集合
        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    /**
     * 点赞
     *
     * @param formDTO
     * @return
     */
    private boolean like(LikeRecordFormDTO formDTO) {
        // 1、查询点赞记录
        Integer count = this.lambdaQuery()
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .eq(LikedRecord::getBizId, formDTO.getBizId())
                .count();

        // 2、判断是否存在，如果已经存在，证明已经点赞过了，直接返回false
        if (count > 0) {
            return false;
        }

        // 3、如果不存在，则新增点赞记录
        // @Accessors(chain = true)
        LikedRecord likedRecord = new LikedRecord()
                .setUserId(UserContext.getUser())
                .setBizId(formDTO.getBizId())
                .setBizType(formDTO.getBizType());

        // @Builder
        /*LikedRecord likedRecord = LikedRecord.builder()
                .userId(UserContext.getUser())
                .bizId(formDTO.getBizId())
                .bizType(formDTO.getBizType())
                .build();*/
        return save(likedRecord);
    }

    /**
     * 取消点赞
     *
     * @param formDTO
     * @return
     */
    private boolean unLike(LikeRecordFormDTO formDTO) {
        return remove(
                Wrappers.<LikedRecord>lambdaQuery()
                        .eq(LikedRecord::getUserId, UserContext.getUser())
                        .eq(LikedRecord::getBizId, formDTO.getBizId())
        );
    }


}
